﻿using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using System.Linq;
using Autofac;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using Flurl.Http;

namespace Pay.Api.Controllers
{
    /// <summary>
    /// 实名
    /// </summary>
    public partial class OpenController : BaseController
    {
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <returns>The merchant.</returns>
        /// <param name="model">Model.</param>
        protected merchant_register_result CreateMerchant(register_model_ex model)
        {
            var register = new register_model
            {
                mobile = model.mobile,
                name = model.name,
                parent_no = model.merchant_no,
                oem_no = model.merchant_no,
                password = "123456H5",
                re_password = "123456H5",
                open_id = model.open_id
            };
            var result = _iMerchantService.Register(register);
            if (result != null)
            {
                return ApiResultToJson.Json("进件成功", new merchant_register_result
                {
                    merchant_no = result.merchant_no,
                    status = result.auth_status,
                    openid = result.openid
                });
            }
            return ApiResultToJson.Json<merchant_register_result>("注册失败");
        }
        /// <summary>
        /// 实名认证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected async Task<ApiResultMessage> VNoCard(fengxinzi_cardno_model model)
        {
            var result = await _iMerchantService.VNoCard(model);
            if (result)
            {
                return new ApiResultMessage("实名认证成功");
            }
            else
            {
                return new ApiResultMessage(0, "实名认证失败");
            }

        }
        /// <summary>
        /// 外放接口的商户进件
        /// </summary>
        /// <returns>The merchant.</returns>
        /// <param name="model">Model.</param>
        protected async Task<merchant_register_result> AuthMerchant(merchant_register_model model)
        {
            if (string.IsNullOrEmpty(model.account_name))
                return ApiResultToJson.Json<merchant_register_result>("户名不能为空");
            if (string.IsNullOrEmpty(model.bank_name))
                return ApiResultToJson.Json<merchant_register_result>("银行名称不能为空");
            if (string.IsNullOrEmpty(model.account_no))
                return ApiResultToJson.Json<merchant_register_result>("账号不能为空");
            if (string.IsNullOrEmpty(model.id_card))
                return ApiResultToJson.Json<merchant_register_result>("身份证不能为空");
            if (string.IsNullOrEmpty(model.mobile))
                return ApiResultToJson.Json<merchant_register_result>("预留手机不能为空");
            string msg = string.Empty;
            //修改通道进件
            merchant_dto binder = null;
            if (!string.IsNullOrEmpty(model.bind_no))
                binder = _iMerchantService.Get(model.bind_no);
            //oem
            var oemer = _iMerchantService.Get(model.merchant_no);
            var oemer_payments = _iMerchantService.GetPayments(oemer.id);
            //判断是否需要通道进件
            var oem_payment = oemer_payments.FirstOrDefault(c => c.payment.channel == model.pay_channel);
            if (oem_payment != null)
            {
                if (oem_payment.payment.is_register)
                {
                    var iPayService = _iocContext.ResolveKeyed<IPayService>(model.pay_channel);
                    merchant_register_dto register = null;
                    var binder_registers = _iMerchantService.GetRegisters(oemer.id);
                    //判断是否进件过了，并且如果是可以进件多次的要用银行卡再判断
                    if (oem_payment.payment.is_more)
                    {
                        model.is_more = oem_payment.payment.is_more;
                        if (binder != null)
                            register = binder_registers.FirstOrDefault(c => (c.pay_channel == model.pay_channel || c.pay_channel == PayChannel.UNIPAY || c.pay_channel == PayChannel.SCORE || c.pay_channel == PayChannel.TopPay) && c.account_no == model.account_no && c.settle_type == model.settle_type);
                    }
                    else
                    {
                        if (binder != null)
                            register = binder_registers.FirstOrDefault(c => (c.pay_channel == model.pay_channel) && c.settle_type == model.settle_type);
                        if (model.pay_channel == PayChannel.Slscore || model.pay_channel == PayChannel.UNIPAY || model.pay_channel == PayChannel.SCORE || model.pay_channel == PayChannel.TopPay)
                        {
                            register = binder_registers.FirstOrDefault(c => (c.pay_channel == model.pay_channel || model.pay_channel == PayChannel.UNIPAY || model.pay_channel == PayChannel.SCORE || model.pay_channel == PayChannel.TopPay) && c.settle_type == model.settle_type);
                        }
                        if (model.pay_channel == PayChannel.Ltd || model.pay_channel == PayChannel.Cj || model.pay_channel == PayChannel.RpayBh127)
                        {
                            //register = merchant.registers.FirstOrDefault(c => c.pay_channel == model.pay_channel && c.id_card == model.id_card);
                            register = _iMerchantService.GetRegister(model.id_card, model.pay_channel);
                        }
                    }
                    string type = "A";
                    if (register != null)
                    {
                        type = "M";
                        model.reg_merchant_no = register.merchant_no;
                    }
                    var result = await iPayService.MerchantRegister(model, type);
                    if (result.result_code != 1000)
                        msg = result.result_msg;
                }
                else
                {
                    model.reg_merchant_no = model.bind_no;
                }
            }
            model.is_patch = true;
            if (!string.IsNullOrEmpty(model.reg_merchant_no))
            {
                string merchant_no = _iMerchantService.MerchantChannelRegister(model);
                if (!string.IsNullOrEmpty(merchant_no))
                    return ApiResultToJson.Json(new merchant_register_result { merchant_no = merchant_no });
            }
            if (!string.IsNullOrEmpty(msg))
                return ApiResultToJson.Json<merchant_register_result>(msg);
            return ApiResultToJson.Json<merchant_register_result>("进件失败");
        }

        /// <summary>
        /// 上传完整的认证信息并创建商户
        /// </summary>
        /// <returns>The merchant.</returns>
        /// <param name="model">Model.</param>
        protected async Task<merchant_register_result> AuthMerchant(verify_auth_model model)
        {
            if (string.IsNullOrEmpty(model.openid))
                return ApiResultToJson.Json<merchant_register_result>("客户端openid不能为空");
            if (string.IsNullOrEmpty(model.account_name))
                return ApiResultToJson.Json<merchant_register_result>("户名不能为空");
            if (string.IsNullOrEmpty(model.bank_name))
                return ApiResultToJson.Json<merchant_register_result>("银行名称不能为空");
            if (string.IsNullOrEmpty(model.account_no))
                return ApiResultToJson.Json<merchant_register_result>("账号不能为空");
            if (string.IsNullOrEmpty(model.id_card))
                return ApiResultToJson.Json<merchant_register_result>("身份证不能为空");
            if (string.IsNullOrEmpty(model.mobile))
                return ApiResultToJson.Json<merchant_register_result>("预留手机不能为空");
            //if (string.IsNullOrEmpty(model.card_positive))
            //	return ApiResultToJson.Json<merchant_register_result>("身份证＋银行卡正面照不能为空");
            //if (string.IsNullOrEmpty(model.card_negative))
            //	return ApiResultToJson.Json<merchant_register_result>("身份证反面照不能为空");
            //if (string.IsNullOrEmpty(model.card_handheld))
            //	return ApiResultToJson.Json<merchant_register_result>("手持身份证+银行卡不能为空");

            var auth_result = _iMerchantService.Auth(model);
            if (auth_result != null)
            {
                var merchant = _iMerchantService.Get(auth_result.merchant_no);
                var regions = _regionService.GetRegionIds(merchant.setting.auth_info.region_id);
                var result = new merchant_register_result { merchant_no = auth_result.merchant_no, openid = auth_result.openid, status = auth_result.status };
                //实名API
                var certify = _iSettingService.Get().certify;
                var cer = certify.FirstOrDefault(c => c.merchant_no == model.merchant_no);
                if (cer != null && auth_result.status == AuthStatusEnum.Wait)
                {
                    var reqData = new certify_verify
                    {
                        merchant_no = model.merchant_no,
                        amount = cer.amount,
                        bank_code = model.bank_code,
                        account_name = model.account_name,
                        account_no = model.account_no,
                        id_card = model.id_card,
                        verify_type = "0040",
                        mobile = model.mobile,
                        bind_no = auth_result.merchant_no,
                        card_type = 1,
                        order_no = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6),
                        pay_channel = PayChannel.Cj
                    };
                    var iPayService = _iocContext.ResolveKeyed<IPayService>(PayChannel.Cj);
                    var api_result = await iPayService.CertifyVerify(reqData);
                    if (api_result.result_code == 1000)
                    {
                        result.status = api_result.status;
                        //注册畅捷用户，获取支行编码
                        //if (result.status == AuthStatusEnum.Auth)
                        //{
                        //    try
                        //    {
                        //        long provice_id = 0, city_id = 0;
                        //        if(regions.Length >= 2)
                        //        {
                        //            provice_id = regions[0];
                        //            city_id = regions[1];
                        //        }
                        //        await RequestMethod.cj_api_url.PostJsonAsync(new
                        //        {
                        //            bind_no = auth_result.merchant_no,
                        //            merchant.setting.auth_info.bank_code,
                        //            provice_id,
                        //            city_id,
                        //            model.account_name,
                        //            model.mobile
                        //        });
                        //    }
                        //    catch
                        //    {
                                
                        //    }
                        //}
                    }
                }
                return ApiResultToJson.Json("进件成功", result);
            }
            return ApiResultToJson.Json<merchant_register_result>("进件失败");
        }

        /// <summary>
        /// 批量上传完整的认证信息并创建商户,不可以批量调用实名认证，是浪费
        /// </summary>
        /// <returns>The merchant.</returns>
        /// <param name="dto">Model.</param>
        protected async Task<verify_auth_ex_result> AuthMerchant(batch_auth_model dto)
        {
            foreach (var model in dto.data)
            {
                if (string.IsNullOrEmpty(model.openid))
                    return ApiResultToJson.Json<verify_auth_ex_result>("客户端openid不能为空");
                if (string.IsNullOrEmpty(model.account_name))
                    return ApiResultToJson.Json<verify_auth_ex_result>("户名不能为空");
                if (string.IsNullOrEmpty(model.bank_name))
                    return ApiResultToJson.Json<verify_auth_ex_result>("银行名称不能为空");
                if (string.IsNullOrEmpty(model.account_no))
                    return ApiResultToJson.Json<verify_auth_ex_result>("账号不能为空");
                if (string.IsNullOrEmpty(model.id_card))
                    return ApiResultToJson.Json<verify_auth_ex_result>("身份证不能为空");
                if (string.IsNullOrEmpty(model.mobile))
                    return ApiResultToJson.Json<verify_auth_ex_result>("预留手机不能为空");
            }
            var merchants = _iMerchantService.Auth(dto);
            var result = new verify_auth_ex_result();
            foreach (var auth_result in merchants)
            {
                //修改通道进件
#if !DEBUG
				//var oem_merchant = _iMerchantService.Get(dto.merchant_no);
				//var merchant = _iMerchantService.Get(auth_result.merchant_no);
				//foreach (var mer_payment in oem_merchant.payments) {
				//	//通道关闭跳过
				//	if (!mer_payment.payment.is_open) continue;
				//	//不需要进件的通道
				//	if (!mer_payment.payment.is_register) continue;
				//	//允许多次进件的跳过
				//	if (mer_payment.payment.is_more) continue;
				//	var iPayService = _iocContext.ResolveKeyed<IPayService>(mer_payment.payment.channel);
				//	foreach (var pay_set in mer_payment.settles) {
				//		//如果APP没有设置此通道跳过
				//		if (!merchant.payments.Any(c => c.payment.id == mer_payment.payment_id)) continue;
				//		string type = (merchant.registers.Any(c => c.pay_channel == mer_payment.payment.channel && c.settle_type == pay_set.settle_type)) ? "M" : "A";
				//		if (type == "A") {
				//			var result2 = await iPayService.MerchantRegister(merchant.id, pay_set.settle_type);
				//		} else {
				//			var result2 = await iPayService.MerchantModify(merchant.id, pay_set.settle_type);
				//		}
				//	}
				//}
#endif
                result.data.Add(new verify_auth_result { merchant_no = auth_result.merchant_no, openid = auth_result.openid, status = auth_result.status });
            }
            return ApiResultToJson.Json(result);
        }

        /// <summary>
        /// 扫码进件
        /// </summary>
        /// <returns>The naive.</returns>
        /// <param name="model">Model.</param>
        public async Task<merchant_register_result> OpenNaive(native_merchant_model model)
        {
            var binder = _iMerchantService.Get(model.bind_no);
            var hf_set = binder.setting.hf_set;
            if (hf_set.open_wx == AuthStatusEnum.Auth)
                return ApiResultToJson.Json<merchant_register_result>("已认证成功过");
            hf_set.category_jd = model.category_jd;
            hf_set.category_wx = model.category_wx;
            hf_set.category_zfb = model.category_zfb;
            hf_set.wx_account = model.wx_account;
            hf_set.open_wx = AuthStatusEnum.Wait;
            hf_set.notify = model.notify;
            binder.setting.shop_info.shop_name = model.shop_name;
            binder.setting.shop_info.region_id = model.region_id;
            binder.setting.shop_info.address = model.address;
            binder.setting.shop_info.business_license = model.business_license;
            int result = 0;//_iMerchantService.Update(merchant);
#if !DEBUG
            var binder_payments = _iMerchantService.GetPayments(binder.id);
            if (binder_payments.Any(c => c.payment.channel == PayChannel.HF)) {
				//var iPayService = _iocContext.ResolveKeyed<IPayService>(PayChannel.HF);
				//if (string.IsNullOrEmpty(merchant.setting.hf_set.t0_native_mchid)) {
				//	var result2 = await iPayService.MerchantRegister(merchant.id, "T0");
				//	merchant.setting.hf_set.t0_native_mchid = result2.merchant_no;
				//} else {
				//	var result2 = await iPayService.MerchantModify(merchant.id, "T0");
				//	merchant.setting.hf_set.t0_native_mchid = result2.merchant_no;
				//}
				//if (string.IsNullOrEmpty(merchant.setting.hf_set.t1_native_mchid)) {
				//	var result2 = await iPayService.MerchantRegister(merchant.id, "T1");
				//	merchant.setting.hf_set.t1_native_mchid = result2.merchant_no;
				//} else {
				//	var result2 = await iPayService.MerchantModify(merchant.id, "T1");
				//	merchant.setting.hf_set.t1_native_mchid = result2.merchant_no;
				//}
				//result += _iMerchantService.Update(merchant);
			}
#endif
            if (result >= 0)
            {
                return ApiResultToJson.Json(new merchant_register_result { merchant_no = binder.merchant_no, openid = binder.openid, status = hf_set.open_wx });
            }
            return ApiResultToJson.Json<merchant_register_result>("失败");
        }


        /// <summary>
        /// 商户总账
        /// </summary>
        /// <returns>The grade.</returns>
        /// <param name="model">Model.</param>
        protected bill_dto GetBill(head_req model)
        {
            var result = _iBillService.GetBill(model);
            if (result != null)
                return result;
            else
                return new bill_dto();
        }

        /// <summary>
        /// 商户账单
        /// </summary>
        /// <returns>The bill details.</returns>
        /// <param name="model">Model.</param>
        protected ApiPagedResult<bill_detail_dto> GetBillDetails(bill_model model)
        {
            var list = _iBillService.GetByBillDetail(model);
            var result = new ApiPagedResult<bill_detail_dto>(list.rows, list.total_result, list.page, list.size);
            return result;
        }

        /// <summary>
        /// 查询商户进件费率
        /// </summary>
        /// <returns>The fee.</returns>
        /// <param name="model">Model.</param>
        protected query_fee_resp QueryFee(query_fee_req model)
        {
            var binder = _iMerchantService.Get(model.bind_no);
            var binder_payments = _iMerchantService.GetPayments(binder.id);
            var payment = binder_payments.FirstOrDefault(c => c.payment.channel == model.pay_channel);
            if (payment == null)
                return ApiResultToJson.Json<query_fee_resp>("商户未进件", 2001);
            var settle = payment.settles.FirstOrDefault(c => c.settle_type == model.settle_type);
            if (settle == null)
                return ApiResultToJson.Json<query_fee_resp>("商户未进件", 2001);
            return ApiResultToJson.Json("获取成功", new query_fee_resp { fee = settle.fee, settle = ((int)(settle.settle * 100)).ToString() });
        }

        /// <summary>
        /// 实名收费列表
        /// </summary>
        /// <returns>The auth info.</returns>
        /// <param name="model">Model.</param>
        protected ApiPagedResult<authinfo_dto> GetAuthInfo(auth_info_query model)
        {
            var merchant = _iMerchantService.Get(model.merchant_no);
            var query = new MemberQuery
            {
                idcard = model.idcard,
                mobile = model.mobile,
                name = model.name,
                end_time = model.end_time,
                start_time = model.start_time,
                page = model.page,
                size = model.size
            };
            var list = _iMerchantService.Get(query);
            var result = new ApiPagedResult<authinfo_dto>(list.rows, list.total_result, list.page, list.size);
            return result;
        }
    }
}
